package dictcn.com.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import dictcn.com.R;

import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class Translate extends ActivityGroup {//翻译界面Activity
	
	 private TextView txt_trans=null;
	 private EditText edit_txt=null;

	 private Button btn_trans_cler=null;
	 private ProgressDialog dlg=null;
	 
	 //有道API访问地址
	 private static final String TRANSLATE_URL="http://fanyi.youdao.com/openapi.do";
	 //语音控件请求结果
	 private static final int VOICE_RECOGNITION_REQUEST_CODE =1001;
	 
	 //异步查询线程（这个是个例子，可以不用异步加载的）
	 private AnsyThread asynThread=null;
	
	 private ImageButton imgBtnTrsCameraj,imgBtnTrsMicj,imgBtnTrsNormalj;
	 
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.translatef);
	        
	    	setupViewComponent();
	    	
	    	//对话框的相应设置
	    	dlg=new ProgressDialog(this);
	    	dlg.setMessage("正在努力加载中……");
	    	dlg.setTitle("提示信息");
	    	dlg.setIndeterminate(false);//设置不确定模式

	    }
	 
	 //初始化关联空间信息
	  private void setupViewComponent(){
		  
		  imgBtnTrsCameraj=(ImageButton)findViewById(R.id.imgBtnTrsCamera);
		  imgBtnTrsMicj=(ImageButton)findViewById(R.id.imgBtnTrsMic);
		  imgBtnTrsNormalj=(ImageButton)findViewById(R.id.imgBtnTrsNormal); 
		  txt_trans=(TextView)findViewById(R.id.txtTrs);
		  edit_txt=(EditText)findViewById(R.id.edTxtTrs);
		  btn_trans_cler=(Button)findViewById(R.id.BtnTrsClear);
		  
		  imgBtnTrsNormalj.setOnClickListener(new onTranslateClickListener());
		  imgBtnTrsMicj.setOnClickListener(new onReadWordsListener());
		  edit_txt.addTextChangedListener(new TextWatcherImpl());
		  
		  //清除按钮的监听
		  btn_trans_cler.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				edit_txt.setText("");
				btn_trans_cler.setText("600");
			}
		});
	  }
	  
	  //编辑框中动态地监听内容的改变并设置清除按钮中字体的显示
	  private class TextWatcherImpl implements TextWatcher{
		  public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			  
			  //设置字体的剩余个数
				btn_trans_cler.setText(String.valueOf(600-s.toString().length()));
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			
		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			
		}
	  }
	  
	 //翻译按钮监听事件
	  private class onTranslateClickListener implements OnClickListener{
		  
		  public void onClick(View v) {
			// TODO Auto-generated method stub
			  String str=edit_txt.getText().toString().trim();
			  
				if(str.equals("")){
					Toast.makeText(Translate.this, "翻译的内容不能为空", Toast.LENGTH_LONG).show();
				}else{
					asynThread=new AnsyThread();//启动异步线程联网获取翻译内容
					asynThread.execute(100);
				}			
		  }
	  }
	  
	  //通过有道API设置相应参数查询翻译结果，返回翻译内容
	  private String transWords(){
		  
		  String resultStr="-1";
		  	HttpPost request=new HttpPost(TRANSLATE_URL);
			List<NameValuePair> params =new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("keyfrom", "michael"));
			params.add(new BasicNameValuePair("key", "1054337575"));
			params.add(new BasicNameValuePair("type", "data"));
			params.add(new BasicNameValuePair("doctype", "xml"));
			params.add(new BasicNameValuePair("version", "1.1"));
			
			//设置要翻译的内容
			params.add(new BasicNameValuePair("q",edit_txt.getText().toString().trim()));
			try {
				request.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
				HttpResponse response=new DefaultHttpClient().execute(request);
				if(response.getStatusLine().getStatusCode()!=404){//网络连接正确
					
					//返回翻译的结果，String类型
					String strTemp=EntityUtils.toString(response.getEntity()).trim();
					
					//以下为对返回结果的解析，由于只需要第一条数据，就直接字符解析了，要获取完整内容建议采用json或者xml解析器解析
					int index1=strTemp.indexOf("]]");
					strTemp=strTemp.substring(index1+6);
					index1=strTemp.indexOf("A[");
					int index2=strTemp.indexOf("]]");
					resultStr=strTemp.substring(index1+2,index2);
				//	txt_trans.setText(strTemp.substring(index1+2,index2));
				}
			} catch (Exception e) {//网络连接失败
				// TODO Auto-generated catch block
				resultStr="-1";
				e.printStackTrace();
			}	
			return resultStr;
	  }
	  
	  //语音结果返回信息
	  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			// TODO Auto-generated method stub
			
			if(requestCode==VOICE_RECOGNITION_REQUEST_CODE && resultCode==RESULT_OK){
			
				//ArrayList表示返回的结果集合
				ArrayList<String> result=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
				int len=result.size();
				
				//获取需要的语音结果信息，一下为获取第一条语音结果信息
				String str[]=null;
				if(len>=5){//如果大于5个结果信息，只选择最前面的5条
					str=new String[]{result.get(0).toString(),result.get(1).toString(),result.get(2).toString(),
							result.get(3).toString(),result.get(4).toString()};
				}else{//信息数小于5条，则选择相应的条数
					str=new String[]{};
					if(len==0)
						Toast.makeText(Translate.this, "无法识别", Toast.LENGTH_LONG).show();
					else{
						for(int i=0;i<len;i++)
							str[i]=result.get(i).toString();
					}
				}
				try{
					if(len!=0){
						
						//编辑框中设置返回的语音结果信息
						edit_txt.setText(result.get(0).toString());
					}
				}catch(Exception e){
					Toast.makeText(Translate.this,"语音无法识别", Toast.LENGTH_SHORT).show();
				}				
			}			
			super.onActivityResult(requestCode, resultCode, data);
		}
	  
	  //语音识别按钮的监听操作
	  private class onReadWordsListener implements OnClickListener{

			public void onClick(View v) {
				// TODO Auto-generated method stub'
				if(isVoiceSoftInstall()){//语音控件已经安装，直接识别
					
					//启动语音对话框控件，监听用户的话
					Intent intent=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
					intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
							RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
					intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Please say something!");
					
					startActivityForResult(intent,VOICE_RECOGNITION_REQUEST_CODE);
					
				}else{//语音控件未安装，提示用户安装
					
					Dialog dlg=new AlertDialog.Builder(Translate.this)
					.setMessage("你没有安装语音插件，是否安装")
					.setNegativeButton("取消", null)
					.setPositiveButton("安装", new DialogInterface.OnClickListener() {				

						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							//通过直接访问语音apk的网站下载语音插件，Uri为下载的地址
							Uri uri=Uri.parse("http://www.apk.anzhi.com/201107/19/com.google.android.voicesearch_32588500_0.apk");
							Intent intent=new Intent();
							intent.setAction(Intent.ACTION_VIEW);
							intent.setData(uri);
							startActivity(intent);			
						}
					})
					.create();
					dlg.show();	
				}
			}
		}
	  public boolean isVoiceSoftInstall(){//判断语音系统在手机中是否安装
		  
			PackageManager pm=getPackageManager();
			List<ResolveInfo> activities=pm.queryIntentActivities(
					new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
			if(activities.size()<=0)
				return false;
			else 
				return true;
		}	
	  
	  //异步线程类，后台获取解析翻译的结果
	  private class AnsyThread extends AsyncTask<Integer, Integer, String>{
		
		  @Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			  
			dlg.show();//提示框的显示
			super.onPreExecute();
		}
		  
		@Override
		protected String doInBackground(Integer... params) {
			// TODO Auto-generated method stub
			return transWords();//获取翻译结果并解析返回
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			dlg.dismiss();//提示框的消失
			if(!result.equals("-1"))
				txt_trans.setText(result);
			super.onPostExecute(result);
		}
	  }
	  
	  //按下返回键，结束当前activity
	  public boolean onKeyDown(int keyCode, KeyEvent event) {
			// TODO Auto-generated method stub
			if(keyCode==KeyEvent.KEYCODE_BACK)
			{
				Translate.this.finish();
			}
			return super.onKeyDown(keyCode, event);
		}
 }

